import os  # 导入 os 模块，以解决 'NameError: name 'os' is not defined' 错误
from flask import Flask, render_template
from config import Config
from models import db
from flask_bootstrap import Bootstrap
from flask_migrate import Migrate
from routes.hierarchy import hierarchy_bp
from routes.requirements import requirements_bp
from routes.communication import communication_bp
from flask_login import LoginManager  # 添加导入
from routes.diagram import diagram_bp
from flask_wtf.csrf import CSRFProtect, generate_csrf

import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
    
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    print(f"数据库连接字符串: {app.config['SQLALCHEMY_DATABASE_URI']}")
    print(f"当前工作目录: {os.getcwd()}")
    print(f"模板路径: {app.template_folder}")
    # 初始化扩展
    db.init_app(app)
    Bootstrap(app)
    Migrate(app, db)

    # 启用CSRF保护
    csrf = CSRFProtect(app)

    # 添加获取CSRF令牌的路由
    @app.route('/csrf-token', methods=['GET'])
    def get_csrf_token():
        return {'csrf_token': generate_csrf()}

    # 注册蓝图
    app.register_blueprint(hierarchy_bp)
    app.register_blueprint(requirements_bp)
    app.register_blueprint(communication_bp)
    app.register_blueprint(diagram_bp)
    # 基础路由
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 添加健康检查路由
    @app.route('/health')
    def health_check():
        return 'OK', 200
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True, port=5000)